<template>
  <div>
    <div style="padding: 5px">
      <el-button type="danger" :disabled="selection.length === 0">删除</el-button>

      <el-button type="primary" icon="el-icon-plus" @click="$router.push({ name: 'ArticleCreate' })">发布新文章</el-button>
    </div>

    <el-table :data="list" v-loading="loading" @selection-change="onSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>

      <el-table-column prop="id" label="文章ID" width="80"></el-table-column>

      <el-table-column prop="title" label="文章标题"></el-table-column>

      <el-table-column prop="user_name" label="作者" width="100"></el-table-column>

      <el-table-column prop="create_time" label="创建时间" width="180"></el-table-column>

      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="{ row }">
          <el-tag v-if="row.status === 0" type="info">待发布</el-tag>

          <el-tag v-else-if="row.status === 1">已发布</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="260" align="center">
        <template slot-scope="{ row }">
          <el-button size="small" type="info" icon="el-icon-edit">编辑</el-button>

          <el-button size="small" type="warning" icon="el-icon-s-promotion" @click="onPublish(row)" :disabled="row.status === 1">发布</el-button>

          <el-button size="small" type="danger" icon="el-icon-delete" @click="onDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination :current-page="page" :total="total" @current-change="onPageChange"></el-pagination>
  </div>
</template>

<script>
export default {
  name: 'index',
  data () {
    return {
      list: [],
      total: 0,
      page: 1,
      limit: 10,
      selection: [],
      loading: true
    }
  },
  mounted () {
    this.onLoad()
  },
  methods: {
    onPageChange (page) {
      this.list = []
      this.page = page
      this.onLoad()
    },
    // 加载列表数据
    onLoad () {
      this.loading = true
      this.$http.get('article', { page: this.page })
        .finally(() => this.loading = false)
        .then(result => {
          this.list = result.list
          this.total = result.total
        })
    },
    // 表格选择项被改变
    onSelectionChange (data) {
      this.selection = data.map(item => {
        return item.id
      })
    },
    // 发布
    onPublish (row) {
      row.status = 1
      this.$message.success('发布成功')
    },
    // 删除
    onDelete (row) {
      this.$confirm('确定要删除这篇文章吗？')
        .then(() => {
          const idx = this.list.findIndex(item => item.id === row.id)
          this.list.splice(idx, 1)
          if (this.list.length <= 3) {
            this.list = []
            this.total = 0
            this.onLoad()
          }
        })
    }
  }
}
</script>

<style scoped>

</style>
